const Question = require("../model/question.model");
const QuestionUser = require("../model/questionUser.model");
class QuestionService {
  // 创建题目
  async createQuestion(
    questionTitle,
    questionAnswer,
    questionType,
    userId,
    questionPreView
  ) {
    const data = {
      questionTitle,
      questionAnswer,
      questionType,
      userId,
      questionPreView,
      lookNum: 0,
    };
    const newQuestion = await Question.create(data);
    return newQuestion.dataValues;
  }
  // 查询题目
  async questionInfo(curentPage, pageSize, type) {
    let data = type === -1 ? {} : { questionType:type };
    let { count, rows } = await Question.findAndCountAll({
      where: data,
      offset: (curentPage - 1) * pageSize, // 查询的起始下标
      limit: pageSize, // 查询的条数
      order: [
        //并针对有效方向列表进行降序排列
        ["createdAt", "DESC"],
      ],
    });
    return {
      count,
      rows,
    };
  }
  // 查询题目内容
  async questionDetail(id) {
    const res0 = await Question.findOne({
      where: { id },
    });
    await Question.update({ lookNum: res0.lookNum + 1 }, { where: { id } });
    const res = await Question.findOne({
      where: { id },
    });
    return res ? res.dataValues : null;
  }
  //检查用户是否收藏
  async isCollect(questionId, userId) {
    const res = await QuestionUser.findOne({
      where: { questionId, userId },
    });
    return res ? res.dataValues : null;
  }
  //创建收藏记录
  async createCollectQuestion(questionId, userId) {
    const data = {
      questionId,
      userId,
    };
    const res = await QuestionUser.create(data);
    return res;
  }
  //删除收藏记录
  async deleteCollectQuestion(questionId, userId) {
    const res = await QuestionUser.destroy({
      where: {
        questionId,
        userId,
      },
    });
    return res;
  }
  //查询收藏的题
  async getCollectQuestion(userId, curentPage, pageSize) {
    const { count, rows } = await QuestionUser.findAndCountAll({
      where: { userId },
      offset: (curentPage - 1) * pageSize, // 查询的起始下标
      limit: pageSize, // 查询的条数
      order: [
        //并针对有效方向列表进行降序排列
        ["createdAt", "DESC"],
      ],
    });
    const questionIdArr = await Promise.all(
      rows.map(
        async (item) =>
          await Question.findOne({
            where: { id: item.questionId },
          })
      )
    );
    return {
      count,
      questionIdArr,
    };
  }
  //hostQuestions
  async hostQuestions() {
    let res = await Question.findAll({
      order: [
        ["lookNum", "DESC"],
      ],
    });
    res = res.slice(0 ,6)
    return res
  }
}

module.exports = new QuestionService();
